package com.sss.ordermodel.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 *  Feign内部调用时带上请求头信息
 *  注意：要去yml里面改变hystrix Feign的隔离策为strategy: SEMAPHORE
 * @author sss
 * @date 2020-04-06 18:19
 **/
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String userAgent = request.getHeader("User-agent");
        String contentType = request.getHeader("Content-Type");
        String token = request.getHeader("token");
        template.header("Content-Type", new String[]{contentType});
        template.header("User-agent", new String[]{userAgent});
        template.header("token", new String[]{token});

//        Enumeration<String> headerNames = request.getHeaderNames();
//        if (headerNames != null) {
//            while (headerNames.hasMoreElements()) {
//                String name = headerNames.nextElement();
//                String values = request.getHeader(name);
//                template.header(name, values);
//            }
//        }
//        Enumeration<String> bodyNames = request.getParameterNames();
//        StringBuffer body =new StringBuffer();
//        if (bodyNames != null) {
//            while (bodyNames.hasMoreElements()) {
//                String name = bodyNames.nextElement();
//                String values = request.getParameter(name);
//                body.append(name).append("=").append(values).append("&");
//            }
//        }
//        if(body.length()!=0) {
//            body.deleteCharAt(body.length()-1);
//            template.body(body.toString());
//        }
    }

}
